package com.itheima.stargraph.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.itheima.stargraph.pojo.User;
import com.itheima.stargraph.utils.JWTUtils;
import com.itheima.stargraph.utils.UserThreadLocalUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用户拦截器
 *
 * @Author mr.zhang
 * Date 2025/6/9 15:16
 */
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断是否是控制层数据
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        //2.获取token
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        //3.判断token是否为空
        if (StrUtil.isBlank(token)){
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            throw new RuntimeException("token为空");
        }
        //4.解析token
        boolean result = JWTUtils.verify(token);
        if (!result){
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            throw new RuntimeException("token解析错误");
        }
        //5.设置用户到本地线程
        User user = JWTUtils.getUser(token);
        UserThreadLocalUtils.setUser(user);
        //6.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocalUtils.remove();
    }
}
